const userDao = require('../dao/userDao.js')
const express = require('express')
const {log} = require('../utils/logger.js')
const userRouter = express.Router()
const axios = require('axios')
const {secretKey,appid} = require('../server.config.js')
const jwt = require('jsonwebtoken');
const secret = '默认密钥'

/**
 * 获得所有的订单
 */
userRouter.get('/getRecords',async (req,res)=>{
    let ans = await userDao.queryRecords()
    ans.conn.end()
    ans.res.forEach(item=>{
        item.detail = JSON.parse(item.detail.replace('\n', ""))
        item.address = JSON.parse(item.address.replace('\n', ""))
    })
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getRecords`)
    res.send(ans.res)
})

/**
 * 通过openid进行登录,并返回用户的用户名和所有的订单数据
 */
userRouter.post('/login/:openid',async (req,res)=>{
    let openid = req.params.openid
    let ans = await userDao.queryUser(openid)
    if(ans.res.length===0){
        ans.conn.end()
        let temp = await userDao.addUser(openid)
        temp.conn.end()
        ans = await userDao.queryUser(openid)
    }
    let user = {}
    user.openid = openid
    user.username = ans.res[0].username
    ans.conn.end()
    ans = await userDao.queryAllRecordsByopenid(openid)
    ans.conn.end()
    user.records = []
    ans.res.forEach(item=>{
        item.detail = JSON.parse(item.detail.replace('\n',''))
        item.address = JSON.parse(item.address.replace('\n',''))
        user.records.push(item)
    })
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/login`)
    res.send(user)
})
/**
 * 获得openid
 */
userRouter.post('/getopenid/:code',async (req,res)=>{
    let code = req.params.code
    let url=`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secretKey}&js_code=${code}&grant_type=authorization_code`
    let ret = await axios.get(url)
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/getopenid`)
    res.send(ret.data.openid)
})

/**
 * 上传新的订单
 */
userRouter.post('/uploadRecord',async (req,res)=>{
    let data = await userDao.addRecord(req.body.recordsId,req.body.openId,req.body.detail,req.body.address,req.body.totalPrice,req.body.username)
    data.conn.end()
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/uploadRecord`)

    res.send(data.res)
})

/**
 * 删除订单通过订单号
 */
userRouter.get('/deleteRecordById/:recordsId',async (req,res)=>{
    let recordsId = req.params.recordsId
    let data = await userDao.deleteRecordById(recordsId)
    data.conn.end()
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/deleteRecordById`)
    res.send(data.res)
})

/**
 * 通过管理员账号查看是否正确
 */
userRouter.get('/checkAccount/:account/:password',async (req,res)=>{
    let data = await userDao.checkAccount(req.params.account)
    data.conn.end()
    log(`来自${req.ip.substring(req.ip.lastIndexOf(':')+1)}的请求,访问了/checkAccount`)
    let ret = false
    if(data.res.length!==0)
        ret = req.params.password==data.res[0].password
    let token = jwt.sign({username:req.params.account,password:data.res[0].password}, secret, {
        expiresIn: '3h'
    });
    let obj = {}
    if(ret){
        obj.status = 1,
        obj.token = token
    }else{
        obj.status = 0
    }
    res.send(obj) 
})
/**
 * 检查token的合法性
 */
userRouter.get('/checkToken/:token',async (req,res)=>{
    let token = req.params.token
    if(token===undefined)
        return res.send('ok')
    jwt.verify(token,secret,(err,decode)=>{
        if(err){
            res.send('no')
        }else
            res.send('ok')
    })
})
module.exports = userRouter